package com.yyy.common.dao;

import com.yyy.tcc.entity.TransferRecord;
import java.math.BigDecimal;
import java.sql.*;

/**
 * 转账记录数据访问层
 */
public class TransferRecordDao {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/distributed_transaction";
    private static final String USER = "root";
    private static final String PASS = "123456";

    /**
     * 创建转账记录
     */
    public boolean createRecord(String transactionId, String fromUserId,
                              String toUserId, BigDecimal amount, String status) throws SQLException {
        String sql = "INSERT INTO transfer_record (transaction_id, from_user_id, to_user_id, amount, status) " +
                    "VALUES (?, ?, ?, ?, ?)";

        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, transactionId);
            stmt.setString(2, fromUserId);
            stmt.setString(3, toUserId);
            stmt.setBigDecimal(4, amount);
            stmt.setString(5, status);

            return stmt.executeUpdate() > 0;
        }
    }

    /**
     * 更新转账记录状态
     */
    public boolean updateStatus(String transactionId, String status) throws SQLException {
        String sql = "UPDATE transfer_record SET status = ? WHERE transaction_id = ?";

        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, status);
            stmt.setString(2, transactionId);

            return stmt.executeUpdate() > 0;
        }
    }

    /**
     * 查询转账记录
     */
    public TransferRecord getByTransactionId(String transactionId) throws SQLException {
        String sql = "SELECT * FROM transfer_record WHERE transaction_id = ?";

        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, transactionId);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    TransferRecord record = new TransferRecord();
                    record.setId(rs.getLong("id"));
                    record.setTransactionId(rs.getString("transaction_id"));
                    record.setFromUserId(rs.getString("from_user_id"));
                    record.setToUserId(rs.getString("to_user_id"));
                    record.setAmount(rs.getBigDecimal("amount"));
                    record.setStatus(rs.getString("status"));
                    return record;
                }
            }
        }
        return null;
    }
}
